﻿function SinaDataProvider() {
    this.url = "http://hq.sinajs.cn/?rn={random}&list={code}"; //Math.random() * 100000
}

SinaDataProvider.prototype.GetStocks = function (codeList) {
    if (codeList == null || codeList == "") return null;
    var sinaCodes = new Array();
    if (typeof (codeList) == "string") {
        var codeArr = codeList.split(",");
        for (var i = 0; i < codeArr.length; i++) {
            sinaCodes.push(this.TransferStockCode(codeArr[i]));
        }
    }
    else {
        for (var i = 0; i < codeList.length; i++) {
            sinaCodes.push(this.TransferStockCode(codeList[i]));
        }
    }
    var StockRssUrl = this.url.replace("{random}", Math.random() * 100000)
                              .replace("{code}", sinaCodes.join());

    var the = this;
    var slist;
    try {
        var request = new XMLHttpRequest();
        request.open("GET", StockRssUrl, false);
        request.send(null);
        slist = this.Parse(request.responseText, sinaCodes);
    }
    catch (Error) {
    }
    return slist;
}

SinaDataProvider.prototype.Parse = function (dataStr, codeArr) {
    //var strList = data.split(/\n/g);
    eval(dataStr);
    var sList = new Array();
    for (s in codeArr) {
        try {
            var data = eval("hq_str_" + codeArr[s] + ".split(',')");
        }
        catch (Error) {
            continue;
        }
        var stock = new StockInfo();
        stock.code = codeArr[s];
        stock.name = data[0];
        stock.todayopen = data[1]; //parseFloat
        stock.yesterday = data[2];
        stock.realprice = data[3];
        stock.maximum = data[4];
        stock.minimum = data[5];
        stock.volume = data[8];
        stock.amount = data[9];
        stock.changeAmt = stock.getChangeAmt();
        stock.changeRate = stock.getChangeRate();
        stock.tradetime = data[30] + "  " + data[31];

        //处理五挡口
        var firstIndex = 10;
        var currIndex = 0
        for (var i = firstIndex; i < firstIndex + 5 * 2; i = i + 2) {
            var vol = parseFloat(data[i]) / 100;
            stock.buyVolumes[currIndex] = vol.toFixed(0);
            stock.buyPrices[currIndex] = data[i + 1];

            currIndex++;
        }

        firstIndex = 20;
        currIndex = 0
        for (var i = firstIndex; i < firstIndex + 5 * 2; i = i + 2) {
            var vol = parseFloat(data[i]) / 100;
            stock.saleVolumes[currIndex] = vol.toFixed(0);
            stock.salePrices[currIndex] = data[i + 1];

            currIndex++;
        }

        sList.push(stock);
    }
    return sList;
}

//type:min daily weekly monthly
SinaDataProvider.prototype.GetChartUrl = function (sCode, type) {
    if (type === undefined || type === "")
        type = "min"
    sCode = this.TransferStockCode(sCode);
    return "http://image.sinajs.cn/newchart/" + type + "/n/" + sCode + ".gif?rn=" + Math.random() * 100000;
}

SinaDataProvider.prototype.GetDetailPageUrl = function (sCode) {
    sCode = this.TransferStockCode(sCode);
    return "http://finance.sina.com.cn/realstock/company/" + sCode + "/nc.shtml?rn=" + Math.random() * 100000;
}


SinaDataProvider.prototype.TransferStockCode = function (stockCode) {
    if (stockCode == null) return "";
    var newCode = stockCode.toLowerCase();
    if (newCode == "") {
        return newCode;
    }
    if (newCode == "999999") {
        newCode = "sh000001";
    }
    else if (newCode == "399001") {
        newCode = "sz399001";
    }
    else if (newCode.indexOf("sh") == 0) { ; }
    else if (newCode.indexOf("sz") == 0) { ; }
    else {
        if (newCode.indexOf("6") == 0) {
            newCode = "sh" + newCode;
        }
        else if (newCode.indexOf("0") == 0) {
            newCode = "sz" + newCode;
        }
        else {
            newCode = "";
        }
    }
    return newCode;
}


//<script>
//	document.write('<script type="text\/javascript" src="http:\/\/hq.sinajs.cn\/?_=' + Math.random() * 100000 + '&list=' + fullcode + '"><\/' + 'script>');
//</script>
//0：”大秦铁路”，股票名字；
//1：”27.55″，今日开盘价；
//2：”27.25″，昨日收盘价；
//3：”26.91″，当前价格；
//4：”27.55″，今日最高价；
//5：”26.20″，今日最低价；
//6：”26.91″，竞买价，即“买一”报价；
//7：”26.92″，竞卖价，即“卖一”报价；
//8：”22114263″，成交的股票数，由于股票交易以一百股为基本单位，所以在使用时，通常把该值除以一百；
//9：”589824680″，成交金额，单位为“元”，为了一目了然，通常以“万元”为成交金额的单位，所以通常把该值除以一万；
//10：”4695″，“买一”申请4695股，即47手；
//11：”26.91″，“买一”报价；
//12：”57590″，“买二”
//13：”26.90″，“买二”
//14：”14700″，“买三”
//15：”26.89″，“买三”
//16：”14300″，“买四”
//17：”26.88″，“买四”
//18：”15100″，“买五”
//19：”26.87″，“买五”
//20：”3100″，“卖一”申报3100股，即31手；
//21：”26.92″，“卖一”报价
//(22, 23), (24, 25), (26,27), (28, 29)分别为“卖二”至“卖四的情况”
//30：”2008-01-11″，日期；
//31：”15:05:32″，时间；


//(function(){

//	var $ = function( id ){
//		return new $.fn( id );
//	}
//	$.fn = function( id ){
//		id = id.replace( "#", "" );
//		this[ 0 ] = document.getElementById( id );
//	}
//	$.fn.prototype = {
//		html	: function( str ){
//			this[ 0 ].innerHTML = str;
//			return this; 
//		},
//		width	: function( n ){
//			this[ 0 ].style.width = n + "px";
//			return this;
//		}
//	};

//	var ST = /ST/i.test( stockname ) , //是否为ST股
//		Bstock = papercode == b_code ? true : false, //B股标志
//		SHBstock = Bstock && /sh/i.test( papercode ), //沪B标志
//		digi = SHBstock ? 3 : 2; //小数保留几位
//		
//	//更新主要信息
//	var realprice = $("#realprice"), changeAmt = $("#changeAmt"), changeRate = $("#changeRate"),
//		tradetime = $("#tradetime"), todayopen = $("#todayopen"), maximum = $("#maximum"), 
//		minimum = $("#minimum"), amplitude = $("#amplitude"), highlimit = $("#highlimit"), 
//		yesterday = $("#yesterday"), volume = $("#volume"), amount = $("#amount"), 
//		turnoverrate = $("#turnoverrate"), downlimit = $("#downlimit"), lyr = $("#lyr"), 
//		ttm = $("#ttm"), pb = $("#pb"), totalvalue = $("#totalvalue"), csv = $("#csv"),
//		fiveRate = $("#fiveRate"), maintop = $("#maintop"),
//		fiveAmt = $("#fiveAmt"), arrow = $("#arrow"), arrowDom = arrow[0];
//			
//	var data = eval( "hq_str_" + fullcode + ".split(',')" ),
//		setlongSuspend = false, suspension = false;
//	
//	function formatNum( n ){
//		return n > 9 ? ( "" +n ) : ("0" + n ); 
//	}	  	
//	function f2( condition, amt, decimal, unit ){
//		amt = parseFloat( amt );
//		return ( condition == 0 || isNaN( amt ) )  ? "--" : ( ( decimal === undefined ? amt : amt.toFixed( decimal ) ) + (unit || "") );
//	}
//	//修改文字颜色
//	var comparePrice = 0;
//	function getDiffCls( amt ){
//		amt = parseFloat( amt );
//		return amt > comparePrice ? "red" : ( amt == comparePrice ? "" : "green" ); 
//	}
//	function timeToInt( timestr ){
//		var time_arr=(timestr || "0:0:0") .split(":");
//		return time_arr[0]*10000+time_arr[1]*100+time_arr[2]*1;
//	}	
//	//长期停牌股票模拟数据
//	if ( data[0] == "" ) {
//		setlongSuspend = true; //只设置一次
//		var d = new Date();
//		data = stockname + ",0.00,0.00,0.00,0.00,0.00,0.00,0.00,0,0,0,0.00,0,0.00,0,0.00,0,0.00,0,0.00,0,0.00,0,0.00,0,0.00,0,0.00,0,0.00," + d.getFullYear()+ "-" + formatNum( (d.getMonth() + 1) ) + "-" + formatNum( d.getDate() ) +"," + formatNum( d.getHours() ) + ":" + formatNum( d.getMinutes() )+ ":" + formatNum( d.getSeconds() );
//		data = data.split(",");
//	}
//	
//	data[3] = parseFloat(data[3]);
//	data[2] = parseFloat(data[2]);
//		  	
//	//判断是否停牌
//	var calAmt = data[3], tickettime =  timeToInt(data[31]);
//	if ( tickettime > 93000 && data[3] ==0 && data[8] == 0 ){
//		suspension = true;
//		calAmt = data[2]; //停牌时用昨收替代现价
//	}else{
//		suspension = false;
//	}
//	if ( tickettime >= 90000 && tickettime< 92500 ){
//		calAmt = data[2]; //9点前到竞价时用昨收替代现价
//	}
//	var diff = data[3] - data[2];
//			
//	todayopen.html( f2( data[3], data[1] ,digi) );		//今日开盘价
//	yesterday.html( f2( data[2], data[2] ,digi) );		//昨日收盘价
//	maximum.html( f2( data[3], data[4],digi) );		//最高成交价
//	minimum.html( f2( data[3], data[5],digi) );		//最低成交价
//	volume.html( f2( data[3], parseInt(data[8]/100), 0, "手") );			//成交数量
//	amount.html( f2( data[3], data[9]/10000, 2, "万" )  );			//成交金额
//	tradetime.html( data[30] + "  " + data[31] );		//行情日期
//	
//	if (!suspension) {
//		realprice.html( f2( data[3], data[3], digi)).width( 79 ); //最近成交价
//		changeAmt.html(data[3] == 0 ? "--" : diff.toFixed( digi )); //涨跌额
//		changeRate.html( data[3] == 0 ? "--" : ( (100 * diff / data[2]).toFixed(2) + "%") ); //涨跌幅
//	}else{
//		changeAmt.html("");
//		changeRate.html("");
//		realprice.html("<a href='http://biz.finance.sina.com.cn/stock/company/notice.php?kind=daily&symbol=" + fullcode +"'>停牌</a>").width( 105 );
//	}
//	
//	comparePrice = parseFloat( data[2] );

//	var cls = data[3] == 0 ? "" : getDiffCls( data[3] );
//	maintop[0].className = cls;
//	
//	amplitude.html( f2( data[3], ((parseFloat(data[4]) - parseFloat(data[5])) * 100) / data[2] , 2, "%" ) );		//振幅
//	//新股上市当天没有涨跌停限制
//	var newStock = /^N/.test( data[0] );
//	highlimit.html( newStock ? "--" : (data[2] * (ST ? 1.05 : 1.1) ).toFixed( digi ) );		//涨停价
//	downlimit.html( newStock ? "--" : (data[2] * (ST ? 0.95 : 0.9) ).toFixed( digi ) );		//跌停价		
//	
//	lyr.html( profit ==0 ? "--" : f2( calAmt, calAmt * totalcapital /10000 / profit, 2 ) );		//市盈率 LYR
//	ttm.html( profit_four ==0 ? "--" : f2( calAmt, calAmt * totalcapital /10000 / profit_four, 2 ) );		//市盈率 TTM	 	
//	pb.html( mgjzc == 0 ? "--" : f2( calAmt, calAmt / mgjzc, 2) );		//市净率	
//	//市值 ＝ 开盘前 ？ 昨日收盘价 × 股本 ： 当前价 × 股本
//	var totalmart= parseFloat(( timeToInt(data[31]) < 93000 ? data[2] : calAmt ) * totalcapital/10000).toFixed( 2 );
//	totalvalue.html( totalmart + "亿" );		//总市值
//	
//	csv.html( f2( calAmt, calAmt * currcapital / 10000 , 2, "亿") );		//流通市值
//	turnoverrate.html( currcapital == 0 ? "0.00%" : f2( data[3], 100 * parseFloat( data[8] ) / (10000 * currcapital) ,2 ,"%" ) );		//换手率
//	
//	todayopen[0].className = data[3] == 0 ? "" : getDiffCls( data[1] );
//	maximum[0].className = data[3] == 0 ? "" : getDiffCls( data[4] );
//	minimum[0].className = data[3] == 0 ? "" : getDiffCls( data[5] );
//	highlimit[0].className = (data[3] == 0 || newStock) ? "" : getDiffCls( data[2] * 1.1 );
//	downlimit[0].className = (data[3] == 0 || newStock) ? "" : getDiffCls( data[2] * 0.9 );
//	
//})();	